package com.hevery.warpper;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @Author: Hevery
 * @Description:
 * @Date: Created on 2017/10/8
 * @Modified By:
 */
public class HttpServletRequestCopier extends HttpServletRequestWrapper {

    private byte[] copy;

    public HttpServletRequestCopier(HttpServletRequest request) throws IOException{
        super(request);
        copy = getBodyString(request).getBytes(request.getCharacterEncoding());
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(copy);
        ServletInputStreamCopier copier = new ServletInputStreamCopier(bais);
        return copier;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));

    }

    public String getBodyString(ServletRequest request) throws IOException{
        StringBuilder builder = new StringBuilder();
        try(InputStream inputStream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))){
            String line = "";
            while ((line = reader.readLine()) != null){
                builder.append(line);
            }
        }
        return builder.toString();
    }
    public byte[] getCopy(){
        return copy;
    }
}
